package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.*;
import cn.itcast.service.system.UserService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.*;

@Controller
@RequestMapping("/cargo/invoice")
public class InvoiceController extends BaseController {
    @Reference
    private InvoiceService invoiceService;

    /**
     * 1. 查询发票列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {

        //根据企业id查询
        PageInfo<Invoice> pageInfo = invoiceService.findByPage(getLoginCompanyId(), pageNum, pageSize);
        //保存
        request.setAttribute("pageInfo", pageInfo);
        return "cargo/invoice/invoice-list";
    }

    /**
     * 2.进入添加页面
     *
     * @param
     * @return
     */

    @Reference
    private ShippingService shippingService;
    @Reference
    private PackingService packingService;
    @Reference
    ExportService exportService;
    @Reference
    private ContractService contractService;

    @RequestMapping("/toAdd")
    public String toAdd(String id) {

        Shipping shipping = shippingService.findById(id);

        if (shipping.getState() == 1) {

            return "redirect:/cargo/shipping/list";
        } else {

            //1.拿报运合同

            //定义一个金额;
            Double invoiceMoney = 0d;

            //拿委托单


            //shipping.get

            //拿到一个装箱单
            Packing packing = packingService.findById(shipping.getShippingOrderId());


            //可能拿到报运单的多个id
            String exportIds = packing.getExportIds();
            String customerContract = "";

            //

            //分割字符串
            String[] array = exportIds.split(",");
            //转成集合
            List<String> exportIdsList = Arrays.asList(array);
//判断
            //定义一个list集合,存储贸易条款
            List<String> list = new ArrayList<>();

//2.
            if (exportIdsList != null && exportIdsList.size() > 0) {

                //一个报运单的遍历
                for (String exportId : exportIdsList) {

                    //通过一个报运单的id查询一个报运单
                    Export export = exportService.findById(exportId);
                    //得到合同号,累加
                    customerContract += export.getCustomerContract() + " ";

                    //一个报运单可能对应多个购销合同
                    //可能得到多个购销合同id

                    String contractIds = export.getContractIds();
                    //分割
                    String[] contractArray = contractIds.split(",");
                    //转成数组
                    List<String> contractIdsList = Arrays.asList(contractArray);

                    //判断
                    if (contractIdsList != null && contractIdsList.size() > 0) {
                        //遍历
                        for (String contractId : contractIdsList) {
                            //拿到一个购销合同
                            Contract contract = contractService.findById(contractId);

                            String tradeTerms = contract.getTradeTerms();

                            if (tradeTerms != null && tradeTerms != "") {
                                //,拿到贸易条款加入到集合
                                list.add(tradeTerms);
                            }

                            //购销合同总金额,累加
                            invoiceMoney += contract.getTotalAmount();

                        }

                    }

                }

            }
            //3.
            //拿贸易条款;
            //list集合去重复值
            List tradeTermsList = removeDuplicate(list);
            //遍历累加
            String tradeTerms = "";
            for (Object o : tradeTermsList) {
                tradeTerms += o + " ";

            }


            Invoice invoice = new Invoice();
            invoice.setScNo(customerContract);
            invoice.setTradeTerms(tradeTerms);
            invoice.setInvoiceMoney(invoiceMoney);
            invoice.setShippingOrderId(id);


            request.setAttribute("invoice", invoice);
            request.setAttribute("customerContract", customerContract);
            request.setAttribute("TradeTerms", tradeTerms);
            request.setAttribute("invoiceMoney", invoiceMoney);
            request.setAttribute("id", id);

        }
        return "cargo/invoice/invoice-add";
    }


    public static List removeDuplicate(List list) {

        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).equals(list.get(i))) {
                    list.remove(j);
                }
            }
        }
        return list;
    }


    @Autowired
    private FileUploadUtil fileUploadUtil;
    @Autowired
    private UserService userService;

    @RequestMapping("/edit")
    public String edit(Invoice invoice, MultipartFile productPhoto) {
        //设置企业id,企业名称
        invoice.setCompanyId(getLoginCompanyId());
        invoice.setCompanyName(getLoginCompanyName());

        //设置创建者部门
        User user = userService.findById(getLoginUser().getId());
        invoice.setCreateDept(user.getDeptName());
        //设置创建人
        invoice.setCreateBy(user.getUserName());
        //添加

        try {
            String url = "http://" + fileUploadUtil.upload(productPhoto);
            invoice.setPickupPhoto(url);
            invoiceService.save(invoice);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return "redirect:/cargo/invoice/list";
    }


    //删除 3.只有当状态为草稿时,才可以删除
    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Integer> delete(String id) {
        // 返回的数据通过map封装
        Map<String, Integer> resultMap = new HashMap<>();
        boolean flag = invoiceService.delete(id);
        if (flag) {
            // 删除成功
            resultMap.put("message", 1);
        } else {
            // 删除失败
            resultMap.put("message", 0);
        }
        return resultMap;
    }


    @Autowired
    private UserService userservice;

    @RequestMapping("/exportPdf")

    public void export(String id) throws Exception {

//1.获取pdf模板文件流
        InputStream in = session.getServletContext().getResourceAsStream("/jasper/text09invoice.jasper");

        //2.获取数据
        Invoice invoice = invoiceService.findById(id);


        //2.1发票编号
         String invoiceNo = invoice.getInvoiceNo();
        //2.2开票日期
        Date createTime = invoice.getCreateTime();

        // String format = new SimpleDateFormat("yyyy-MM-dd").format(createTime);


        //2.3部门名称
        String createDept = invoice.getCreateDept();
        //2.4贸易条款
        String tradeTerms = invoice.getTradeTerms();
        //2.5金额
        Double invoiceMoney = invoice.getInvoiceMoney();
        //6.开票人,谁使用这个系统开票人就是谁
        User user = userservice.findById(getLoginUser().getId());
        String userName = user.getUserName();
        //7.购买方,拿到委托单的id,查询购销合同,有个字段是offeror
        Shipping shipping = shippingService.findById(invoice.getShippingOrderId());

        //8.收货人地址 拿到委托单id再拿装箱单id,再拿报运单id,查询consignee字段

        //9.同上拿备注


        //3.构造数据,map中的键要对应Parameters的参数名
        Map<String, Object> map = new HashMap<>();

         map.put("invoiceNo", invoiceNo);
        map.put("createTime", createTime);
        map.put("createDept", createDept);
        map.put("tradeTerms", tradeTerms);
        map.put("invoiceMoney", invoiceMoney);
        map.put("creator", userName);
        map.put("companyName", getLoginCompanyName());
        map.put("offeror", shipping.getNotifyParty());
        map.put("consignee", shipping.getPortOfDischar());
        map.put("remarks", shipping.getRemark());

        //4.创建jasperPrint对象,用于往模板中填充数据

        //第一个参数,模板文件流
        //第二个参数,填充数据用途,用map填充
        //第三个参数.,填充数据用途,通过的数据源填充
        JasperPrint jasperPrint = JasperFillManager.fillReport(in, map, new JREmptyDataSource());


        //5.Pdf导出
        //设置编码
        response.setCharacterEncoding("utf-8");
        //设置下载响应头,固定格式
        response.setHeader("content-disposition", "attachment;fileName=export.pdf");
        ServletOutputStream out = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, out);
        out.close();
    }


}
